package cn.bdqn.fast.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * Druid连接池工具
 */
public class DruidUtil {
    public static DataSource dataSource; //数据源
//    private static Connection connection;
    public static ThreadLocal<Connection> threadLocal
        = new ThreadLocal<Connection>(); //本地线程 一个线程共享一个变量
    static {
        try {
            //加载属性集配置文件
            InputStream inputStream = DruidUtil.class.getClassLoader().
                    getResourceAsStream("database.properties");
            Properties properties = new Properties();
            properties.load(inputStream); //读取文件内容
            //创建数据源工厂
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    /**
     * 获取数据源
     * @return
     */
    public static DataSource getDataSource(){
        return dataSource;
    }
    /**
     * 获取数据库连接对象
     */
    public static Connection getConnection(){
        Connection connection = null;
        try {
            connection = threadLocal.get();
            if(connection == null){
                connection = dataSource.getConnection();
                threadLocal.set(connection);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }
    /**
     * 关闭连接
     */
    public static void close(){
        Connection connection = null;
        try {
            connection = threadLocal.get();
            if(connection != null){
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

//    public static void main(String[] args) {
//        System.out.println(DruidUtil.getConnection());
//        System.out.println(DruidUtil.getConnection());
//        System.out.println(DruidUtil.getConnection());
//    }
}
